<?php

namespace App\Services\Store\User;

use App\Exceptions\LoginException;
use App\Exceptions\SmsException;
use App\Exceptions\UserException;
use App\Models\Store\User\UserModel;
use App\Services\Applet\Other\SmsService;
use Exception;
use Illuminate\Support\Facades\DB;

class UserService extends BaseUserService
{
    const WHITE_LIST_PHONE_DEFAULT_CODE = 123456;    // 白名单手机号对应的默认验证码

    const AVATAR_DEFAULT = 'https://www.baidu.com/link?url=OS-2zUgsz2uq2AjPyw01aq8j8fg15SjBLtzBpjMilm7R8zeXeLazdmaLK2uLkB53Yfio4TYfFiKFNKBEvKvqpaYM2n18gZYWEiZhLILwAFaEE3zJrzK2npiDhUmQG-VfzqSmzbXVcjQQ2iJqm3-Vx-i4OmIask07InJvc1c1mIKfolo5Kx0BPg-oLpDaQ9KXdYlnuKim48jZZhC9OB6yIzIxPhzqlgi8CxaPCh3yJLqNFGie9YUgc0_nEuED50MU-6lDQxIPKTzijV3-pKQBxcJWd8ZRXn1_A6uvp3ttcGoi5gQ2XLZj1R_QBne9_N7z4jRQEv1qq2CzcP2JECy79h2uvpkxzRCpyPyeawy8lp0zhNnvLNfI-vb6ZvwjEKtp6mgvE9yDR_3bdlTjKTotD6pblgL92PUYnbHIBQdPK1cC3iE4LbCsqRkEDU808NL4746QA_Nw52kIjHewlxI5IOL_FopJeEOhisIdRewKDz2hfWTop88bKph-q9fM0Z2Chwfq3HetV-phSCBCIFtN3ge0x75XlOI6jCny2CF_EL_v4cNMzQqf63dI0Em3EgSL7mpJ8eITivDg_CFy-eUversgadIj2o5X5c4EduufOznyYVb4hKUMAjjSigZTL3EM4g7xxPxpwTZplvXwq4YlKtfx3QWkyH-Oy_oRxlw7nAy&wd=&eqid=a2ffbe780684aa3e000000066767a77b';


    /**
     * 注册
     * @param array $params
     * @return void
     * @throws SmsException
     * @throws UserException
     * @throws Exception
     */
    public function register(array $params)
    {
        //  检测验证码尝试次数
        $this->checkCodeCheckCount(SmsService::CODE_TYPE_CLIENT_LOGIN, $params['phone'], function () {
            throw new SmsException('操作频率过高，请稍后重试', SmsException::CODE_1301);
        });

        // 检测登录验证码
        $this->checkCodeCache($params['phone'], $params['verifyCode']);

        // 验证两次密码是否一致
        if ($params['password'] != $params['qrPassword']) {
            throw new UserException('密码不一致', UserException::CODE_1000);
        }

        // 判断用户是否存在
        $userData = $this->getStoreUserModel()->getItemByPhone($params['phone']);
        if ($userData) {
            throw new UserException('用户已存在', UserException::CODE_1000);
        }

        // 密码加密
        $password = encryption($params['password']);

        $createUserData = [
            'phone' => $params['phone'],
            'password' => $password,
            'real_name' => $params['realName'],
            'avatar' => $params['avatar'] ?? self::AVATAR_DEFAULT,
            'id_card' => $params['idCard'],
            'status' => UserModel::STATUS_WAIT_APPLY,
        ];

        $createIdCard = [
            'front_img_url' => $params['frontImgUrl'],
            'back_img_url' => $params['backImgUrl'],
        ];

        $createBranch = [
            'name' => $params['ranchName'],
            'province_id' => $params['provinceId'],
            'city_id' => $params['cityId'],
            'region_id' => $params['regionId'],
            'address' => $params['address'],
        ];

        DB::transaction(function () use ($createUserData, $createIdCard, $createBranch) {
            // 创建用户信息
            $userId = $this->getStoreUserModel()->addItemGetId($createUserData);
            // 创建身份证数据
            $createIdCard['store_user_id'] = $userId;
            $this->getStoreUserIdCardModel()->addItem($createIdCard);
            // 创建牧场信息
            $createBranch['store_user_id'] = $userId;
            $this->getStoreRanchModel()->addItem($createBranch);
            // 用户申请入驻记录
            $this->getUserApplyRecordsModel()->addItem([
                'store_user_id' => $userId,
            ]);
        });

    }

    /**
     * 登录
     * @param array $params
     * @return array
     * @throws LoginException
     * @throws Exception
     */
    public function login(array $params): array
    {
        // 判断用户是否存在
        $userData = $this->getStoreUserModel()->getItemByPhone($params['phone'], [
            'id', 'password', 'real_name', 'status'
        ]);
        if (empty($userData)) {
            throw new LoginException('用户名或密码错误', LoginException::CODE_1001);
        }
        if (!encryptionCheck($params['password'], $userData['password'])) {
            throw new LoginException('用户名或密码错误', LoginException::CODE_1001);
        }
        if ($userData['status'] == UserModel::STATUS_WAIT_APPLY) {
            throw new LoginException('入驻审核中', LoginException::CODE_1015);
        }

        $userInfo = [
            'userId' => $userData['id'],
            'nickName' => $userData['real_name'],
        ];

        // 生成登录 token       @tips 用户权限修改后需要重新登录
        $token = generateJwt($userInfo, self::USER_TYPE_STORE);

        return [
            'user' => $userInfo,
            'token' => $token,
        ];
    }

    /**
     * 忘记密码
     * @return void
     * @throws Exception
     */
    public function resetPassword(array $params)
    {
        // 检测验证码尝试次数
        $this->checkCodeCheckCount(SmsService::CODE_TYPE_CLIENT_LOGIN, $params['phone'], function () {
            throw new SmsException('操作频率过高，请稍后重试', SmsException::CODE_1301);
        });

        // 检测登录验证码
        $this->checkCodeCache($params['phone'], $params['verifyCode']);

        // 验证两次密码是否一致
        if ($params['password'] != $params['qrPassword']) {
            throw new UserException('密码不一致', UserException::CODE_1000);
        }

        // 判断用户是否存在
        $userData = $this->getStoreUserModel()->getItemByPhone($params['phone'], [
            'id', 'password', 'real_name', 'status'
        ]);
        if (empty($userData)) {
            throw new UserException('用户不存在', UserException::CODE_1003);
        }
        if ($userData['status'] != 0) {
            throw new LoginException('登陆失败! 用户被禁止登录!', LoginException::CODE_1002);
        }

        // 重新生成密码
        $password = encryption($params['password']);

        $this->getUserModel()->updateItemById($userData['id'], [
            'password' => $password,
        ]);
    }
}
